package com.study.mall.mallproduct.service.impl;

import com.study.mall.mallproduct.entity.PmsCategory;
import com.study.mall.mallproduct.mapper.PmsCategoryMapper;
import com.study.mall.mallproduct.service.PmsCategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品三级分类 服务实现类
 * </p>
 *
 * @author admin
 * @since 2022-03-05
 */
@Service
public class PmsCategoryServiceImpl extends ServiceImpl<PmsCategoryMapper, PmsCategory> implements PmsCategoryService {

    @Override
    public List<PmsCategory> listWithTree() {
            List<PmsCategory> entities = baseMapper.selectList(null);

            List<PmsCategory> level1 = entities.stream().filter((pmsCategory) -> {
                return pmsCategory.getParentCid() == 0;
            }).map((menu) -> {
                menu.setChildren(getChildren(menu, entities));
                return menu;
            }).sorted((menu1, menu2) -> {
                return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
            }).collect(Collectors.toList());
            return level1;
    }

    @Override
    public void removeMenuByIds(Long[] asList) {
        baseMapper.deleteBatchIds(Arrays.asList(asList));
    }

    //查找子菜单
    private List<PmsCategory> getChildren (PmsCategory root,List<PmsCategory> all){
        List<PmsCategory> children = all.stream().filter(PmsCategory -> {
            return PmsCategory.getParentCid().equals(root.getCatId());
        }).map(PmsCategory -> {
            PmsCategory.setChildren(getChildren(PmsCategory,all));
            return PmsCategory;
        }).sorted((menu1,menu2) -> {
            return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort());
        }).collect(Collectors.toList());

        return children;
    }
//    @Override
//    public List<PmsCategory> testList() {
//        List<PmsCategory> entities = baseMapper.selectList(null);
//        List<PmsCategory> level1 = new ArrayList<>();
//        for (PmsCategory category : entities){
//            if (category.getParentCid()== 0){
//                level1.add(category);
//                category.setChildren(testgetChildren(category,entities));
//            }
//        }
//        return level1;
//    }

    private List<PmsCategory> testgetChildren(PmsCategory root,List<PmsCategory> all){
        List<PmsCategory> children = new ArrayList<>();
        for (PmsCategory category : all){
            if (category.getParentCid().equals(root.getCatId())){
                category.setChildren(testgetChildren(category,all));
                children.add(category);
            }
        }
        return children;
    }


}
